package com.yuyang.wifi;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.fanjun.keeplive.KeepLive;
import com.fanjun.keeplive.config.ForegroundNotification;
import com.fanjun.keeplive.config.ForegroundNotificationClickListener;
import com.fanjun.keeplive.config.KeepLiveService;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;
import com.yuyang.wifi.activitys.NewMainHomeActivity;
import com.yuyang.wifi.activitys.mine.LockScreenActivity;
import com.yuyang.wifi.activitys.web.WebViewSecretActivity;
import com.yuyang.wifi.base.BaseActivity;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.dialog.BaseDialogFragment;
import com.yuyang.wifi.dialog.UserProtocolDialog;
import com.yuyang.wifi.jobservice.AppService;
import com.yuyang.wifi.jobservice.KeepAliveJobService;
import com.yuyang.wifi.model.AdTypeInfoModel;
import com.yuyang.wifi.model.AdTypeInfoResult;
import com.yuyang.wifi.model.ProtocolModel;
import com.yuyang.wifi.model.ProtocolResult;
import com.yuyang.wifi.model.ShowIconResult;
import com.yuyang.wifi.utils.ActivityAllManager;
import com.yuyang.wifi.utils.AppIconUtil;
import com.yuyang.wifi.utils.DeviceInfoUtils;
import com.yuyang.wifi.utils.MPermissionUtils;
import com.yuyang.wifi.utils.PreferencesProviderUtils;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.eventbus.BaseEvent;
import com.yuyang.wifi.utils.eventbus.BaseEventManager;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yuyang.wifi.utils.DatePickerUtil.getCurrentTimestap;

public class SplashActivity extends BaseActivity implements SplashADListener {

    private FrameLayout mSplashContainer;
    private static final String TAG = "SplashActivity";
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3000;
    private TTAdManager ttAdManager;
    private TTAdNative mTTAdNative;
    private int minSplashTimeWhenNoAD = 2000;

    /**
     * 记录拉取广告的时间
     */
    private long fetchSplashADTime = 0;
    private Handler handler = new Handler(Looper.getMainLooper());
    private SplashAD splashAD;
    private boolean isAdJump = false;
    private String csjKaiPingChannel;
    private String mYlhKaiPingChannel;

    @Override
    protected void initActionBar() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            boolean result = fixOrientation();
            // XLog.i(XLog.BASE, "onCreate fixOrientation when Oreo, result = " + result);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initContentView() {

        mSplashContainer = (FrameLayout) findViewById(R.id.splash_container);
        //resuful();//恢复icon
        // changeLuncher();
        String ischangeIcon = PreferencesProviderUtils.getString(SplashActivity.this, "change_icon", AppConstant.KEY_CHANGE_ICON, "");
        if (!TextUtils.isEmpty(ischangeIcon) && "change_icon".equals(ischangeIcon)) {
            finish();
        } else {
            showIcon();
            String registerTime = SpUtil.find(AppConstant.KEY_REGISTER_TIME);
            if (TextUtils.isEmpty(registerTime)) {
                Long currentTimestap = getCurrentTimestap();
                String registerTimes = String.valueOf(currentTimestap);
                SpUtil.saveOrUpdate(AppConstant.KEY_REGISTER_TIME, registerTimes);
            }

            String userProtocol = SpUtil.find(AppConstant.KEY_USER_PROTOCOL);
            if (TextUtils.isEmpty(userProtocol)) {
                getProtocolUrl();
            }

            String agreeProtocol = SpUtil.find(AppConstant.KEY_AGREE_PROTOCOL);
            if (TextUtils.isEmpty(agreeProtocol)) {
                showUserProtocolDialog();
            } else {
                requestCameraPermission();
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(new Intent(this, AppService.class));
            } else {
                startService(new Intent(this, AppService.class));
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                KeepAliveJobService.startJob(this);
            }
        }
    }

    private void showIcon() {
        RxDataInstance.getInstance().initMap(SplashActivity.this);
        HttpManager.getInstance().getApi().showIcon(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<ShowIconResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<ShowIconResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        //com.yuyang.wifi.utils.ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(ShowIconResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            String showIcon = result.getData().getShowIcon();
                            if (!TextUtils.isEmpty(showIcon) && "1".equals(showIcon)) {
                                // SpUtil.saveOrUpdate(AppConstant.KEY_CHANGE_ICON, "1");
                                PreferencesProviderUtils.putString(MyApplication.getInstance(), "change_icon", AppConstant.KEY_CHANGE_ICON, "change_icon");
                            } else {
                                PreferencesProviderUtils.putString(MyApplication.getInstance(), "change_icon", AppConstant.KEY_CHANGE_ICON, "");
                                // SpUtil.saveOrUpdate(AppConstant.KEY_CHANGE_ICON, "");
                            }
                        } else {
                            //ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                        }
                    }
                });

    }

    private void getProtocolUrl() {
        RxDataInstance.getInstance().initMap(SplashActivity.this);
        HttpManager.getInstance().getApi().getProtocolUrl(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<ProtocolResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<ProtocolResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(ProtocolResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            ProtocolModel data = result.getData();
                            if (null != data) {
                                String privacyagreement = data.getPrivacyagreement();
                                String useragreement = data.getUseragreement();
                                SpUtil.saveOrUpdate(AppConstant.KEY_USER_PROTOCOL, useragreement);
                                SpUtil.saveOrUpdate(AppConstant.KEY_PRIVACY_PROTOCOL, privacyagreement);
                            }
                        } else {
                            ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                        }
                    }
                });
    }

    private void showUserProtocolDialog() {
        UserProtocolDialog userProtocolDialog = UserProtocolDialog.newInstance();
        userProtocolDialog.setData(SplashActivity.this);
        userProtocolDialog.showDialog(SplashActivity.this.getFragmentManager());
        userProtocolDialog.setOnDialogListener(new BaseDialogFragment.DialogListener() {
            @Override
            public void onConfirm() {
                //同意
                userProtocolDialog.dismiss();
                SpUtil.saveOrUpdate(AppConstant.KEY_AGREE_PROTOCOL, "123");
                requestCameraPermission();
            }

            @Override
            public void onInputConfirm(String... values) {
                String privacyProtocol = SpUtil.find(AppConstant.KEY_PRIVACY_PROTOCOL);
                //隐私协议
                Intent intent2 = new Intent(SplashActivity.this, WebViewSecretActivity.class);
                intent2.putExtra("url", privacyProtocol);
                intent2.putExtra("title", "隐私协议");
                startActivity(intent2);
            }

            @Override
            public void onCancel() {
                //不同意
                ToastUtils.showShortToast(SplashActivity.this, "请您阅读并同意该协议，否则无法使用");
            }

            @Override
            public void onSendCode() {
                String userProtocol = SpUtil.find(AppConstant.KEY_USER_PROTOCOL);
                Intent intent = new Intent(SplashActivity.this, WebViewSecretActivity.class);
                intent.putExtra("url", userProtocol);
                intent.putExtra("title", "用户协议");
                startActivity(intent);
            }
        });

    }

    /**
     * 修改App icon
     * Created by ysr on 2017/10/10 14:05.
     * 邮箱 yangshirong@log56.com
     */
    private void changeLuncher() {
        String name = "com.ysr.appiconchange.newsLuncherActivity";
        PackageManager pm = getPackageManager();
        //去除旧图标，不去除的话会出现2个App图标
        pm.setComponentEnabledSetting(getComponentName(),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        //显示新图标
        pm.setComponentEnabledSetting(new ComponentName(SplashActivity.this, name),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
        if (Build.VERSION.SDK_INT < 29) {
            // 禁用Alias1Activity
            AppIconUtil.disableComponent(this, name);
        }
        //Intent 重启 Launcher 应用
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        List<ResolveInfo> resolves = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo res : resolves) {
            if (res.activityInfo != null) {
                android.app.ActivityManager am = (android.app.ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.killBackgroundProcesses(res.activityInfo.packageName);
            }
        }
        // Toast.makeText(this, "桌面图标已恢复", Toast.LENGTH_LONG).show();
    }

    private void resuful() {
        String name = "com.yuyang.wifi.SplashActivity";
        PackageManager pm = getPackageManager();
        //去除旧图标，不去除的话会出现2个App图标
        pm.setComponentEnabledSetting(getComponentName(),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        //显示新图标
        pm.setComponentEnabledSetting(new ComponentName(SplashActivity.this, name),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

        //Intent 重启 Launcher 应用
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        List<ResolveInfo> resolves = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo res : resolves) {
            if (res.activityInfo != null) {
                android.app.ActivityManager am = (android.app.ActivityManager) getSystemService(ACTIVITY_SERVICE);
                am.killBackgroundProcesses(res.activityInfo.packageName);
            }
        }
        // Toast.makeText(this, "桌面图标已更换", Toast.LENGTH_LONG).show();
    }

    private void getAdTypeInfo() {
        RxDataInstance.getInstance().initMap(SplashActivity.this)
                .put("entryNumber", "1");
        HttpManager.getInstance().getApi().getAdTypeInfo(RxDataInstance.getInstance().getParamMap())
                .compose(RxUtil.<AdTypeInfoResult>bindLifecycleAndApplySchedulers(this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<AdTypeInfoResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @Override
                    public void onDataNext(AdTypeInfoResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            AdTypeInfoModel data = result.getData();
                            if (null != data) {
                                int type = data.getType();
                                if (type == 1) {
                                    initCSJAdAppId();//穿山甲开屏广告
                                } else if (type == 2) {
                                    initYLHAdAppId();
                                }
                            } else {
                                initCSJAdAppId();//穿山甲开屏广告
                            }
                        } else {
                            ToastUtils.showShortToast(SplashActivity.this, result.getErrorMessage());
                        }
                    }
                });
    }

    public void initCSJAdAppId() {
        if (ttAdManager == null) {
            ttAdManager = TTAdSdk.getAdManager();
        }
        if (mTTAdNative == null) {
            mTTAdNative = ttAdManager.createAdNative(MyApplication.getInstance());
        }
        loadSplashAd();
    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        fetchSplashADTime = System.currentTimeMillis();
        csjKaiPingChannel = "887530216";
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = null;
        adSlot = new AdSlot.Builder()
                .setCodeId(csjKaiPingChannel)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .build();
        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
                Log.d(TAG, String.valueOf(message));
                /**
                 * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
                 * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
                 * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
                 **/
                long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
                long shouldDelayMills = alreadyDelayMills > minSplashTimeWhenNoAD ? 0 : minSplashTimeWhenNoAD
                        - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
                // 计算出还需要延时多久
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isAdJump = true;
                        goToMainActivity();
                    }
                }, shouldDelayMills);
                //ToastUtils.showShortToast(SplashActivity.this, message);
                //loadSplashAd();
                //goToMainActivity();
            }

            @Override
            @MainThread
            public void onTimeout() {
//                ToastUtils.showShortToast(SplashActivity.this, "开屏广告加载超时");
                //loadSplashAd();
                //goToMainActivity();
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                Log.d(TAG, "开屏广告请求成功");
                mSplashContainer.setVisibility(View.VISIBLE);
                if (ad == null) {
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                if (view != null && mSplashContainer != null && !SplashActivity.this.isFinishing()) {
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    mSplashContainer.addView(view);
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    //ad.setNotAllowSdkCountdown();
                } else {
                    goToMainActivity();
                }

                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
                        Log.d(TAG, "onAdClicked");
                        // ToastUtils.showShortToast(SplashActivity.this, "开屏广告点击");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
                        Log.d(TAG, "onAdShow");
                        // ToastUtils.showShortToast(SplashActivity.this, "开屏广告展示");
                    }

                    @Override
                    public void onAdSkip() {
                        Log.d(TAG, "onAdSkip");
                        // ToastUtils.showShortToast(SplashActivity.this, "开屏广告跳过");
                        goToMainActivity();

                    }

                    @Override
                    public void onAdTimeOver() {
                        Log.d(TAG, "onAdTimeOver");
                        // ToastUtils.showShortToast(SplashActivity.this, "开屏广告倒计时结束");
                        goToMainActivity();
                    }
                });
                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {
                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
                                // ToastUtils.showShortToast(SplashActivity.this, "下载中...");
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                            // ToastUtils.showShortToast(SplashActivity.this, "下载暂停...");
                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                            // ToastUtils.showShortToast(SplashActivity.this, "下载失败....");

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                            //ToastUtils.showShortToast(SplashActivity.this, "下载完成...");
                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {
                            //ToastUtils.showShortToast(SplashActivity.this, "安装完成...");
                        }
                    });
                }
            }
        }, AD_TIME_OUT);

    }

    /*优量汇代码*/
    private void initYLHAdAppId() {
//        if (Build.VERSION.SDK_INT >= 23) {
//            checkAndRequestPermission();
//        } else {
//            // 如果是Android6.0以下的机器，建议在manifest中配置相关权限，这里可以直接调用SDK
//            fetchSplashAD(this, 0);
//        }
        fetchSplashAD(this, 0);
    }

    /**
     * ----------非常重要----------
     * <p>
     * Android6.0以上的权限适配简单示例：
     * <p>
     * 如果targetSDKVersion >= 23，那么建议动态申请相关权限，再调用广点通SDK
     * <p>
     * SDK不强制校验下列权限（即:无下面权限sdk也可正常工作），但建议开发者申请下面权限，尤其是READ_PHONE_STATE权限
     * <p>
     * READ_PHONE_STATE权限用于允许SDK获取用户标识,
     * 针对单媒体的用户，允许获取权限的，投放定向广告；不允许获取权限的用户，投放通投广告，媒体可以选择是否把用户标识数据提供给优量汇，并承担相应广告填充和eCPM单价下降损失的结果。
     * <p>
     * Demo代码里是一个基本的权限申请示例，请开发者根据自己的场景合理地编写这部分代码来实现权限申请。
     * 注意：下面的`checkSelfPermission`和`requestPermissions`方法都是在Android6.0的SDK中增加的API，如果您的App还没有适配到Android6.0以上，则不需要调用这些方法，直接调用广点通SDK即可。
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<String>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        // 快手SDK所需相关权限，存储权限，此处配置作用于流量分配功能，关于流量分配，详情请咨询商务;如果您的APP不需要快手SDK的流量分配功能，则无需申请SD卡权限
        if (!(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        // 如果需要的权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            fetchSplashAD(this, 0);
        } else {
            // 否则，建议请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }


    /**
     * 拉取开屏广告，开屏广告的构造方法有3种，详细说明请参考开发者文档。
     *
     * @param adListener 广告状态监听器
     * @param fetchDelay 拉取广告的超时时长：取值范围[3000, 5000]，设为0表示使用广点通SDK默认的超时时长。
     */
    private void fetchSplashAD(SplashADListener adListener, int fetchDelay) {
        mYlhKaiPingChannel = "7092027049688696";
        fetchSplashADTime = System.currentTimeMillis();
        splashAD = new SplashAD(SplashActivity.this, mYlhKaiPingChannel, adListener, 0);
        splashAD.fetchAndShowIn(mSplashContainer);
//        if(loadAdOnly) {
//            splashAD.fetchAdOnly();
//        }else{
//            splashAD.fetchAndShowIn(adContainer);
//        }
    }

    @Override
    public void onADPresent() {
        Log.i("AD_DEMO", "SplashADPresent");
    }

    @Override
    public void onADClicked() {
        Log.i("AD_DEMO", "SplashADClicked clickUrl: "
                + (splashAD.getExt() != null ? splashAD.getExt().get("clickUrl") : ""));
    }

    /**
     * 倒计时回调，返回广告还将被展示的剩余时间。
     * 通过这个接口，开发者可以自行决定是否显示倒计时提示，或者还剩几秒的时候显示倒计时
     *
     * @param millisUntilFinished 剩余毫秒数
     */
    @Override
    public void onADTick(long millisUntilFinished) {
        Log.i("AD_DEMO", "SplashADTick " + millisUntilFinished + "ms");

    }

    @Override
    public void onADExposure() {
        Log.i("AD_DEMO", "SplashADExposure");
    }

    @Override
    public void onADLoaded(long expireTimestamp) {
        Log.i("AD_DEMO", "SplashADFetch expireTimestamp: " + expireTimestamp
                + ", eCPMLevel = " + splashAD.getECPMLevel());
        mSplashContainer.setVisibility(View.VISIBLE);
        // ToastUtils.showShortToast(SplashActivity.this,"广告加载完成");

    }

    @Override
    public void onADDismissed() {
        Log.i("AD_DEMO", "SplashADDismissed");
        goToMainActivity();
    }

    @Override
    public void onNoAD(AdError error) {
        final String str = String.format("LoadSplashADFail, eCode=%d, errorMsg=%s", error.getErrorCode(),
                error.getErrorMsg());
        Log.i("AD_DEMO", str);
        //fetchSplashAD(this, 0);
        /**
         * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
         * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
         * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
         **/
        long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
        long shouldDelayMills = alreadyDelayMills > minSplashTimeWhenNoAD ? 0 : minSplashTimeWhenNoAD
                - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
        // 计算出还需要延时多久
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                goToMainActivity();
            }
        }, shouldDelayMills);
    }

    private void goToMainActivity() {
        startActivity(new Intent(SplashActivity.this, NewMainHomeActivity.class));
        ActivityAllManager.getInstance().finishAllActivityExcept(SplashActivity.this);
    }

    private boolean isPagerServiceRunning() {
        android.app.ActivityManager manager = (android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (android.app.ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.service.LiveWallpaperService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    //请求相机权限
    private void requestCameraPermission() {
        MPermissionUtils.requestPermissionsResult(this, Constants.PERMISSION_CAMERA,
                new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        getAdTypeInfo();
                        //showIcon();
                    }

                    @Override
                    public void onPermissionDenied() {

                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            // XLog.i(XLog.BASE, "avoid calling setRequestedOrientation when Oreo.");
            return;
        }
        super.setRequestedOrientation(requestedOrientation);
    }


    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventMain(BaseEvent baseEvent) {
        super.onMessageEventMain(baseEvent);
        String tagString = baseEvent.getTagString();
        Log.e("TAG", "reason:===== " + tagString);
        Bundle bundle = (Bundle) baseEvent.getData();
        switch (tagString) {
            case "hint_icon":
                changeLuncher();
                finish();
                break;
        }
    }
}
